package com.yuandm.wxnt;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.yuandm.wxnt.util.Sptools;

import org.json.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;



public class NewsDetailsActivity extends Activity
{
	private final int FINISH = 0;
	private boolean isTuPian = false;
	private String mNid;
	private TextView mNewsDetails;
	private ImageView mTuPian;
	private String TpUrl;
	private String title;
	public String id;
	public String time;
	public String digest;
	private String NewsUrl;
    ProgressDialog progressDialog;
	

	@SuppressLint("HandlerLeak")
	private Handler h = new Handler(){

		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.arg1)
			{
			case FINISH:
                progressDialog.cancel();
				mNewsDetails.setText(Html.fromHtml(msg.obj.toString()));
//                WebView show = (WebView)findViewById(R.id.show);
//                show.loadDataWithBaseURL(null,msg.obj.toString(),"text/html","utf-8",null);
				break;
			}
		}

	};

	@SuppressLint("HandlerLeak")
	private Handler h1 = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.arg1)
			{
			case FINISH:
				mTuPian.setImageBitmap((Bitmap)msg.obj);
				break;
			}
		}

	};
	private IWXAPI api;
	private Button regBtn;
	private Button regBtn_friend;

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newsdetails);

        progress("数据加载中", "请稍等......");
		
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		
//		String categoryName = bundle.getString("categoryName");
//		TextView titleBarTitle = (TextView) findViewById(R.id.newsdetails_titlebar_title);
//		titleBarTitle.setText(categoryName);
		
		
		//获取前面传来的newsDate，这个里面含有从splash里获取的pic地址
		title = bundle.getString("title");
		id = bundle.getString("id");
		TpUrl = bundle.getString("pic");
		time = bundle.getString("time");
		digest = bundle.getString("digest");

		TextView newsTitle = (TextView)findViewById(R.id.news_body_title);
		newsTitle.setText(title);


		//下面是微信分享用的url
		NewsUrl = "http://jrnt.zdmdg.com/Home/Caiji/share?id="+id;

		TextView newsPtimeAndSource = (TextView)findViewById(R.id.news_body_ptime_source);
		newsPtimeAndSource.setText(time + "    " + "今日南通");

		mNid = id;

		//Log.v("id",""+mNid);

		mNewsDetails = (TextView)findViewById(R.id.news_body_details);

		mTuPian = (ImageView)findViewById(R.id.tupian);

		new updateNews().start();
		new updateTp().start();

		initView();
	}



	private void share(int flag){
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);
		api.registerApp(Constants.APP_ID);

		WXWebpageObject webpage = new WXWebpageObject();
	    webpage.webpageUrl = NewsUrl;
	    //Log.v("url",""+NewsUrl);
	    WXMediaMessage msg = new WXMediaMessage(webpage);
	    msg.title = title;
	    msg.description = digest;
	    //这里替换一张自己工程里的图片资源
	    if(isTuPian&&null != ((BitmapDrawable)mTuPian.getDrawable()).getBitmap())
	    {
	    	mTuPian.setDrawingCacheEnabled(true);  //这一句很重要
	    	Bitmap tupian =  mTuPian.getDrawingCache();
	    	Bitmap thumb = ThumbnailUtils.extractThumbnail(tupian, 80, 80);
	    	msg.setThumbImage(thumb);
	    	//Log.v("图片",""+tupian);
	    }
	    else
	    {
		    Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
		    msg.setThumbImage(thumb);
	    }

	    SendMessageToWX.Req req = new SendMessageToWX.Req();
	    req.transaction = String.valueOf(System.currentTimeMillis());
	    req.message = msg;
	    req.scene = flag==0?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
	    api.sendReq(req);
	}

	private void initView(){
    	regBtn = (Button) findViewById(R.id.reg_btn);
		regBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				share(1);

			}
		});

		regBtn_friend = (Button) findViewById(R.id.reg_btn_friend);
		regBtn_friend.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				share(0);

			}
		});
	}
	
	
	
	
	private class updateNews extends Thread{

		@Override
		public void run() {
			String newsBody = getNewsBody();

			while(""==newsBody) //网络不佳时会收不到列表数据
			{
				newsBody=getNewsBody();
			}

			Message msg = h.obtainMessage();
			msg.arg1 = FINISH;
			msg.obj = newsBody;
			h.sendMessage(msg);
		}

	}
	
	private String getNewsBody()
	{
		String retStr = "";
		SyncHttp syncHttp = new SyncHttp();
		String url = "http://jrnt.hengzecn.com/Home/Caiji/show_content";
		String params = "id="+mNid;    //网址中的id

		try
		{
			String retString = syncHttp.httpGet(url, params);

			Sptools.setString(NewsDetailsActivity.this, mNid, retString);

			JSONObject jsonObject = new JSONObject(retString);

			JSONObject dataObject = jsonObject.getJSONObject("data");
			JSONObject newsObject = dataObject.getJSONObject("news");
			retStr = newsObject.getString("content");


		} catch (Exception e)
		{
			String jsonCache = Sptools.getString(NewsDetailsActivity.this, mNid, "");
			try
			{
				JSONObject jsonObject = new JSONObject(jsonCache);

				JSONObject dataObject = jsonObject.getJSONObject("data");
				JSONObject newsObject = dataObject.getJSONObject("news");
				retStr = newsObject.getString("content");
			} catch (Exception b)
			{
				b.printStackTrace();
			}
		}
		return retStr;
	}
	
	
	private class updateTp extends Thread{

		@Override
		public void run() {
			Bitmap TpBody = getTuPian(TpUrl);
			//System.out.print(TpUrl);
			isTuPian = true;
			Message msg = h1.obtainMessage();
			msg.arg1 = FINISH;
			msg.obj = TpBody;
			h1.sendMessage(msg);
		}

	}
	
	public static Bitmap getTuPian(String url){
        URL myFileURL;
        Bitmap bitmap=null;
        try{
            myFileURL = new URL(url);
            HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
            conn.setConnectTimeout(6000);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        return bitmap;

    }

    public void progress(String title,String message){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
        progressDialog.setMessage(message);
        progressDialog.setTitle(title);

        progressDialog.setMax(100);
        progressDialog.show();
    }
}
